import com.sun.tools.javac.Main;

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;

public class FoodPanel extends JPanel {
    //public static final int DIAMETER = (int) (MainFrame.GRID_WIDTH);
    public static int[] foodPoint = new int[]{-1, -1};

    public FoodPanel() {
        //System.out.println("foodpanel");
        setBounds(0, 0, MainFrame.WIDTH, MainFrame.WIDTH);
        setOpaque(false);
    }

    /**
     * 绘制面板的内容: 创建 JPanel 后会调用一次该方法绘制内容,
     * 之后如果数据改变需要重新绘制, 可调用 updateUI() 方法触发
     * 系统再次调用该方法绘制更新 JPanel 的内容。
     */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if (foodPoint[0] == -1 ) {
            //System.out.println("drawfood");
            drawFood(g, 0);
        } else {
            drawFood(g, 1);
        }
    }

    /**
     * 生成食物
     *
     * @param g    Graphics
     * @param mode 模式   0：随机位置生成；
     *             1：固定位置生成（与上次相同）
     */
    private void drawFood(Graphics g, int mode) {
        int[] xPoints;
        int[] yPoints;

        if (mode == 0) {
            //生成x,y随机数
            int rand1 = (int) (-(MainFrame.GRID_NUMBER / 2) + Math.random() * (MainFrame.GRID_NUMBER + 1));
            int rand2 = (int) (-(MainFrame.GRID_NUMBER / 2) + Math.random() * (MainFrame.GRID_NUMBER + 1));

            xPoints = new int[]{MainFrame.SPAWN_POINT[0] + MainFrame.STEP * rand1, MainFrame.SPAWN_POINT[0] + MainFrame.STEP * rand1};
            yPoints = new int[]{MainFrame.SPAWN_POINT[1] + MainFrame.STEP * rand2, MainFrame.SPAWN_POINT[1] + MainFrame.STEP * rand2};
        } else {
            //固定位置生成（与上次相同）
            xPoints = new int[]{foodPoint[0], foodPoint[0]};
            yPoints = new int[]{foodPoint[1], foodPoint[1]};
        }
        //System.out.println("food :" + xPoints[0] + "," + yPoints[0]);
        //判断生成的食物位置不与蛇重叠
        if (MainFrame.xyPoint.contains(xPoints[0] + "," + yPoints[0])) {
            //System.out.println("食物重叠");
            drawFood(g, 0);//如果重叠，重新生成
        } else {
            foodPoint[0] = xPoints[0];
            foodPoint[1] = yPoints[0];
            // 创建 Graphics 的副本, 需要改变 Graphics 的参数,
            // 这里必须使用副本, 避免影响到 Graphics 原有的设置
            Graphics2D g2d = (Graphics2D) g.create();

            // 抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 设置画笔颜色
            g2d.setColor(Color.WHITE);
            // 多点绘制折线
            int nPoints = xPoints.length;
            //System.out.println("点的个数： "+nPoints);
            BasicStroke bs3 = new BasicStroke((float) (MainFrame.GRID_WIDTH * 0.8));// 笔画的轮廓（画笔宽度为格子的80%）
            g2d.setStroke(bs3);

            g2d.drawPolyline(xPoints, yPoints, nPoints);

            // 自己创建的副本用完要销毁掉
            g2d.dispose();
        }
    }
}
